package com.gentics.labs.nop;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Similarity;
import org.apache.lucene.search.TopDocCollector;

public class CRSearcher {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CRSearcher searcher = new CRSearcher("index");
		searcher.search("gentics");
	}

	private IndexSearcher searcher;
	private StandardAnalyzer analyzer;
	
	public CRSearcher(String path) {
		IndexReader reader;
		try {
			reader = IndexReader.open(path);
			searcher = new IndexSearcher(reader);
			analyzer = new StandardAnalyzer();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void search(String query) {
		try {			
			QueryParser parser = new QueryParser("content", analyzer);
			Query parsedQuery = parser.parse(query);
			
			runSearch(parsedQuery);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void runSearch(Query parsedQuery) {
		try {
		    // Collect enough docs to show 5 pages
		    TopDocCollector collector = new TopDocCollector(30);
		    searcher.search(parsedQuery, collector);
		    ScoreDoc[] hits = collector.topDocs().scoreDocs;
	
		    System.out.println("hits: " + hits.length);
			for(int i = 0 ; i < hits.length ; i++) {
				Document doc = searcher.doc(hits[i].doc);
				
				String contentid = doc.get("contentid");
				String name = doc.get("name");
				System.out.println("contentid: " + contentid + " / name: " + name);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
